import Notice from './Notice.vue'
import Vue from 'vue'

let myNotice = Vue.extend(Notice);

let instance;
let instances = [];
let id = 0;

export default function notice(options) {
  // 初始化
  id = 'notification_' + id++;

  // console.log(options)
  // 实例化
  instance = new myNotice({
    // 把传入的options和组件data中的数据合并
    data: options
  });
  // 此时options已经改变，替换为合并后的数据
  // console.log(options)

  // 赋id
  instance.id = id;
  // 手动挂载
  instance.$mount(); // dom渲染完成
  // 手动挂载到body
  document.body.append(instance.$el);

  if (options['duration'] !== 0) {
    // console.time()
    (function (el, id) {
      setTimeout(() => {
        document.body.removeChild(el);
        notice.close(id);
        // console.timeEnd()
      }, options['duration'])
    })(instance.$el, instance.id)
  }

  let verticalOffset = options.offset || 0;
  instances.forEach(item => {
    verticalOffset += item.$el.offsetHeight + 16;
  });
  verticalOffset += 16;
  instance.$el.style.top = verticalOffset + "px";
  instance.verticalOffset = verticalOffset;
  instances.push(instance);
  // console.log(verticalOffset)

  return instance;
}

notice.close = function (id) {
  let index = -1;
  const len = instances.length;
  const instance = instances.filter((instance, i) => {
    if (instance.id === id) {
      index = i;
      return true;
    }
    return false;
  })[0];
  if (!instance) return;

  const removedHeight = instances[index].$el.offsetHeight;
  console.log(removedHeight)
  instances.splice(index, 1);

  if (len <= 1) return;

  for (let i = index; i < len - 1; i++) {
    instances[i].$el.style.top = (instances[i].verticalOffset - removedHeight) + "px";
    instances[i].verticalOffset = instances[i].verticalOffset - removedHeight;
  }
}
